<template>
  <div>

    <div v-if="$route.path=='/user'||$route.path=='/demo'" id="user">

      <view-box ref="viewBox" style="height:100%;">
        <x-header :left-options="{backText: ''}" style="color:white" title="use prop:title">
          <span slot="overwrite-title">个人中心</span>
          <a href="./#/racelist" style="font-size:24px" slot="right">
            <i class="fa fa-home fa-fw"></i>
          </a>
        </x-header>

        <div class="userinfo">
          <group>
            <cell title="头像" link='/userinfo/editportrait' is-link>
              <div>
                <img slot="icon" width="80" style="display:block;" :src="avatar">
                <!-- <span style="color: green">220</span> -->
              </div>
            </cell>
            <cell link='/userinfo/editname' :border-intent="false" title="名字" :value="name" is-link value-align="right">
              <!-- <img slot="icon" width="20" style="display:block;margin-right:5px;" src="http://www.spoorts.cn/static/images/per-head-exp.png"> -->
            </cell>

            <cell title="绑定的资料" is-link :border-intent="false" :arrow-direction="showContent001 ? 'up' : 'down'" @click.native="showContent001 = !showContent001"></cell>

            <template v-if="showContent001">

              <div id='bind-message' v-for='(item,index) in list1' :key='index'>

                <form-preview :body-items="item.list" :footer-buttons="item.buttons">

                </form-preview>

              </div>

              <cell-box @click.native="goLink('improve_user_information')" style="height:30px;text-align: center;color:#1AAD19;" align-items=‘center’>
                <div class='add-icon' style="text-align: center;width: 100%;line-height: 10px;">
                  <x-icon type="ios-plus-outline" size="30"></x-icon>
                </div>
              </cell-box>
            </template>
          </group>

        </div>

        <div>
          <scroller v-if='!isShowBaoming' height="-310" lock-x scrollbar-y :scroll-bottom-offset='0' use-pullup @on-pullup-loading="load" ref="demo1" v-model="demo4Value">

            <div>
              <Signedlist v-for='(item,index) in listData' :key='index' :data1='item' :idnumber='item.idnum'></Signedlist>
              <!-- <Mypreview v-if='item' v-for='(item,index) in listData' :key='index' :list='item'></Mypreview> -->
            </div>

            <div v-if='!stop&&!isShowBaoming' slot="pullup" class="xs-plugin-pullup-container xs-plugin-pullup-up" style="position: absolute; width: 100%; height: 40px; bottom: -40px; text-align: center;">
              <span v-show="demo4Value.pullupStatus === 'default'"></span>
              <span class="pullup-arrow" v-show="demo4Value.pullupStatus === 'default' || demo4Value.pullupStatus === 'up' || demo4Value.pullupStatus === 'down'" :class="{'rotate': demo4Value.pullupStatus === 'down'}">↑</span>
              <span v-show="demo4Value.pullupStatus === 'loading'">
                <spinner type="ios-small">11</spinner>
              </span>
            </div>

          </scroller>

          <!-- <div style="text-align: center" v-if='show'>
            <p style="margin-top: 30px;">您没有报名</p>
          </div> -->
        </div>

        <!-- <myFooter :page="pageConfig"></myFooter> -->
      </view-box>

    </div>

    <!-- 修改头像 -->
    <div v-if="$route.path=='/userinfo'" id="userinfo">
      <div class="userinfo">
        <x-header slot="header" :left-options="{backText: ''}" style="" title="我">
          <a href="./#/racelist" style="font-size:24px" slot="right">
            <i class="fa fa-home fa-fw"></i>
          </a>
        </x-header>
        <group>
          <cell title="头像" link='/userinfo/editportrait' is-link>
            <div>
              <img slot="icon" width="80" style="display:block;" :src="avatar">
              <!-- <span style="color: green">220</span> -->
            </div>
          </cell>
          <cell link='/userinfo/editname' :border-intent="false" title="名字" :value="name" is-link value-align="right">
            <!-- <img slot="icon" width="20" style="display:block;margin-right:5px;" src="http://www.spoorts.cn/static/images/per-head-exp.png"> -->
          </cell>

          <cell title="绑定的资料" is-link :border-intent="false" :arrow-direction="showContent001 ? 'up' : 'down'" @click.native="showContent001 = !showContent001"></cell>

          <template v-if="showContent001">

            <div id='bind-message' v-for='(item,index) in list' :key='index'>

              <form-preview :body-items="item.list" :footer-buttons="item.buttons">

              </form-preview>

            </div>

            <cell-box @click.native="goLink('improve_user_information')" style="height:30px;text-align: center;color:#1AAD19;" align-items=‘center’>
              <div class='add-icon' style="text-align: center;width: 100%;line-height: 10px;">
                <x-icon type="ios-plus-outline" size="30"></x-icon>
              </div>
            </cell-box>
          </template>
        </group>

      </div>
      <myFooter></myFooter>
    </div>
    <!-- 修改姓名 -->
    <div v-if="$route.path=='/userinfo/editname'">
      <x-header slot="header" :left-options="{backText: ''}" style="" title="设置名字">
        <a @click="saveName()" href="javascript:void(0)" style="font-size:  18px" slot="right">
          完成
        </a>
      </x-header>
      <group>
        <x-input @change="fileChanged" v-model="name" type="text" />
      </group>
    </div>

    <div v-if="$route.path=='/userinfo/editportrait'">
      <x-header class='needsclick' :right-options="{showMore: true}" @on-click-more="editPortrait()" slot="header" :left-options="{backText: ''}" style="" title="修改头像">
        <a href="./#/racelist" style="font-size:24px" slot="right">
        </a>
      </x-header>

      <upfile ref="input" style="display:none" name="label" placeholder="placeholder" :src="'//api.ihuipao.com/stor/base64'" :index="0" @fileChange="fileChangeSelf" :defaultstate="defaultstate">
      </upfile>

      <group>
        <img style="width:100%" :src="avatar" alt="">
      </group>

    </div>

    <div v-transfer-dom>
      <confirm v-model="show" :close-on-confirm="false" title="请输入验证码" @on-confirm="post">
        <x-input v-model="code" id='postcode' placeholder="填写验证码" class="weui-vcode">
          <x-button :disabled='clock' @click.native="countDown" slot="right" type="primary" mini>{{codeMessage}}</x-button>
        </x-input>

      </confirm>
    </div>
    <myFooter></myFooter>
  </div>

</template>


<script type="text/ecmascript-6">
/* eslint-disable*/
const url = "//img.ihuipao.cn/";
const countTime = 60; //倒数计时60秒
//默认头像
const headimg =
  "//img.ihuipao.cn/image/png/c6a22affc455904cc8a780f8b3cec1d5.png";
//let host = "http://jiangtao.v3.ihuipao.com/";

import Signedlist from "@/common/components/signedlist.vue";
import Myheader from "@/common/components/myheader.vue";
import { cookie } from "vux";
import MyFooter from "@/common/components/myfooter.vue";
import Upfile from "@/common/components/upfile.vue";

//let clock1 = 1
var isMini;
//判断环境 是否在小程序
var checkIsFromMiniProgram = function() {
  wx.miniProgram.getEnv(function(res) {
    console.log("minprogram:" + res.miniprogram); // true
    //  alert(JSON.stringify(res));
    if (res.miniprogram === true) {
      isMini = true;
      // alert('isMiniprogram:' + res.miniprogram);
    } else {
      isMini = false;
      // alert("========公众号");
    }
  });
};

import {
  Scroller,
  ViewBox,
  Spinner,
  Confirm,
  Icon,
  XHeader,
  CellBox,
  debounce,
  XInput,
  Group,
  XButton,
  Grid,
  GridItem,
  FormPreview,
  Cell,
  LoadMore,
  Actionsheet,
  Toast,
  TransferDomDirective as TransferDom
} from "vux";
//axios
import qs from "qs";
import { axios } from "@/api/axios.js";
import { indexedDB } from "@/api/indexedDB.js";
import mixin from "@/common/js/mixin";
import { isIdNumber, setTitle, hiddenInfo } from "@/common/js/main.js";
import { setTimeout } from "timers";
import Mypreview from "@/common/components/mypreview.vue";

export default {
  mixins: [mixin],
  props: ["page", "host"],
  data() {
    return {
      pageIndex: 5,
      pageConfig: window.pageConfig,
      demo4Value: {
        pullupStatus: "default"
      },
      stop: false,
      listData: [],
      name: "",
      config: {
        perpage: 5, //分页数量
        page: 1, //当前页数
        hasmorepage: false //是否还有分页
      },
      avatar: "//img.ihuipao.cn/image/png/c6a22affc455904cc8a780f8b3cec1d5.png",
      defaultstate: "",
      userName: "",
      isShow: false,
      list1: [],
      list: [],
      showContent001: false,
      show: false,
      code: "", //验证码
      clock: false, //验证码状态锁
      codeMessage: "发送验证码", //验证码倒数数字
      bidTel: "",
      bidId: "",
      hidelogout: false,
      isShowBaoming: false
    };
  },
  computed: {},
  beforeCreate() {
    if (this.$route.query._sid && this.$route.query._token) {
      //如果链接带有_sid 就更新_sid

      window.localStorage.setItem("isLogin", "true");
      cookie.set("_sid", this.$route.query._sid);
      //alert("链接上获取_sid是" + cookie.get("_sid"));
    }

    //alert('链接上获取的sid'+this.$route.query._sid)

    //cookie.set("_sid",this.$route.query._sid)
    //alert('更新_sid'+ cookie.get("_sid"))
  },
  created() {
    if (
      //如果没有_sid就去登录
      typeof cookie.get("_sid") == "undefined" ||
      window.localStorage.getItem("isLogin") == "false"
    ) {
      this.$router.push({ path: "login" });
    } else {
      //获取用户信息
      this.getUserInfo();
    }

    window.localStorage.setItem("isQuery", "false");
    this.getList();
    checkIsFromMiniProgram();

    if (!!isMini) {
      this.hidelogout = true;
    }
  },
  mounted() {},
  methods: {
    userApply1(id, index, raceMessage) {
      return this.axios.post(
        //`${host}registration/fetch`,
        `${host}user/auth/regitration`,
        qs.stringify({
          account: window.localStorage.getItem("account"),
          raceid: id
        })
      );
    },
    getList(config) {
      let _this = this;
      config = Object.assign({ perpage: this.config.perpage }, config);

      if (!!this.stop) {
        return;
      }
      //alert(this.pageIndex)

      config = {
        page: this.pageIndex
      };

      axios.post(`${host}user/auth/mysign`, qs.stringify(config)).then(
        response => {
          if (response.data.code == "200") {
            //console.log(response.data.data)
            //console.log("--");
            //console.log(this.show1);

            //console.log(response);

            if (
              response.data.data.total == 0 ||
              typeof response.data.data.total == "undefined"
            ) {
              this.isShowBaoming = true;
              this.show1 = true;
            }

            //console.warn(response.data.data.total);

            //this.stop = true;

            // response.data.data.data.forEach((item, index) => {
            //   this.list.forEach((item1, index1) => {
            //     if (item.id == item1.id) {
            //       response.data.data.data.splice(index,1)
            //     }
            //   });
            // });
            //console.warn(response.data.data.data);

            //var myarray = [];

            // var _reduce = function(array, key) {
            //   var arr = array;
            //   var hash = {};
            //   arr = arr.reduce(function(item, next) {
            //     hash[next[key]]
            //       ? ""
            //       : (hash[next[key]] = true && item.push(next));
            //     return item;
            //   }, []);
            //   return arr;
            // };

            //alert(JSON.stringify(_reduce(this.list , "src")))
            //myarray = this.list.concat(response.data.data.data);
            //console.warn('过滤前')
            //console.warn(myarray)
            //myarray = _reduce(myarray, "id");
            //console.warn('过滤后')
            //console.warn(myarray)
            //this.list = myarray;

            this.total = response.data.total;

            //this.list=this.list.concat(response.data.data.data)
            //console.log(this.list);
            this.list = response.data.data.data;
            if (this.list.length == 0) {
              this.isShowBaoming = true;
            }

            let array = [];

            //this.list  首先获取 我所报名的赛事

            this.list.forEach((item, index) => {
              array.push(_this.userApply1(item.id, index));
            });
            /*
            axios.all(getpagelist).then(
              axios.spread(function() {
                // Both requests are now complete
                for (let i = 0; i < arguments.length; i++) {
                  _this.content.push(arguments[i].data.data.content);
                }
                _this.showContent = true;
              })
            );
            */

            //再根据才是 获取报名信息
            let arrayList = [];
            axios.all(array).then(
              axios.spread(function(response) {
                //console.log("-+-+-+-+-+-+");
                //console.log(arguments);
                //console.log(arguments)
                var newlist = [];
                var newlist1=[]

                for (let i = 0; i < arguments.length; i++) {
                  //console.log(arguments[i].data.code)
                  if (arguments[i].data.code == 200) {
                    newlist.push(arguments[i]);
                    newlist1.push(_this.list[i])
                  }
                }

                //console.log(newlist)
                //console.log(newlist1)
                
                
                
                //console.log('123')
                //console.log(newlist)
                for (let i = 0; i < newlist.length; i++) {
                  //_this.list[i].message = arguments[i].data.data;

                  if (newlist[i].data.code == 200) {
                    //console.log(_this.list[i])
                    axios
                      .post(
                        `${host}race/events`,
                        qs.stringify({ raceid: newlist1[i].id })
                      )
                      .then(response1 => {
                        if (response1.data.code == "200") {
                          var event;
                          //console.log("---");
                          //console.log(response1.data);
                          response1.data.data.forEach((item, index) => {
                            //console.log('-+-+')
                            //console.log(item)
                            //console.log(newlist[i].data.data[0].eventid)
                            if (item.id == newlist[i].data.data[0].eventid) {
                              event = item;
                            }
                          });

                          let obj = {};

                          obj = newlist[i].data.data[0];
                          obj.event = event;

                          obj.raceMessage = _this.list[i];

                          //arrayList.push(obj)
                          arrayList[i] = obj;
                          arrayList.push([])
                          arrayList.pop()

                          _this.demo4Value.pullupStatus = "default";

                          if (_this.pageIndex >= response.data.data.total) {
                            _this.stop = true;
                          }
                          _this.show1 = true;
                        } else {
                        }
                      });
                  }
                }

                _this.$set(_this, "listData", arrayList);
              })
            );

            //在用报名信息的eventid 找到赛事信息
          } else {
            if (response.data.code == "0") {
              this.isShowBaoming = true;
              this.show1 = true;
            } else {
              this.$vux.toast.show({
                type: "warn",
                text: response.data.msg
              });
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    load() {
      let _this = this;
      this.demo4Value.pullupStatus = "up";

      this.pageIndex += 5;

      this.getList(this.searchConfig);

      this.$nextTick(() => {
        setTimeout(function() {
          _this.$refs.demo1.reset();
        }, 3000);
      });
    },
    pay() {
      window.location.href =
        "https://wechat.ihuipao.com/qrpay?openid=" +
        window.localStorage.getItem("openid");
    },
    goLink(path) {
      this.$router.push({ path: path });
    },
    post() {
      let _this = this;
      //检查解绑原来手机号是验证手机号信息有效性
      this.axios
        .post(
          `${host}user/auth/bind/checkcodevalid`,
          qs.stringify({
            mobile: this.bidTel,
            code: this.code
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            _this.$router.push({
              path: `improve_user_information?bid=${this.bidId}`
            });
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
    },
    countDown() {
      if (this.clock) {
        return;
      }

      this.sendCode();
      this.clock = true;
      let _this = this;
      this.codeMessage = countTime;
      let countDown = setInterval(function() {
        //console.log(_this.codeMessage)
        if (_this.codeMessage <= 1) {
          _this.codeMessage = "发送验证码";
          _this.clock = false;
          clearInterval(countDown);
          return;
        }
        _this.codeMessage--;
      }, 1000);
    },
    sendCode() {
      this.axios
        .post(
          `${window.host}user/sms/send`,
          qs.stringify({
            mobile: this.bidTel,
            type: "bind"
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            this.$vux.toast.show({
              type: "success",
              text: "验证码发送成功"
            });
          }
        });
    },
    fileChangeSelf(e) {
      this.saveAvatar(e);
      //console.log(e)
    },
    saveAvatar(e) {
      this.axios
        .post(
          `${window.host}user/auth/uploadimg`,
          qs.stringify({
            filepathname: `${e.files[e.files.length - 1]}`
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            this.avatar = "//img.ihuipao.cn/" + e.files[e.files.length - 1];
            //console.log(this.avatar);
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
    },
    getUserInfo() {
      let _this = this;
      //alert(cookie.get("_sid"));
      //alert(this.$route.query._token)

      //this.axios.post(`http://api.ihuipao.com/user/current`).then(response => {
      if (this.$route.query._token) {
        var config = {
          _token: this.$route.query._token
        };
      } else {
        var config = {};
      }

      this.axios
        .post(`${host}user/current`, qs.stringify(config))
        .then(response => {
          //alert(JSON.stringify(response));
          if (response.data.code == "200") {
            if (response.data.data.length == 0) {
              window.localStorage.setItem("isLogin", "false");
              cookie.remove("_sid");
              this.$vux.toast.show({
                type: "warn",
                text: "没有此用户信息",
                onHide() {
                  _this.$router.push({
                    path: "login"
                  });
                }
              });
            }
            window.localStorage.setItem("account", response.data.data.account);
            window.localStorage.setItem("type", response.data.data.platform);
            //alert(response.data.data)
            //alert(response.data.data.name)
            //alert(response.data.data.avatar)
            this.name = !!response.data.data.name
              ? response.data.data.name
              : "默认姓名";
            this.avatar = !!response.data.data.avatar
              ? url + response.data.data.avatar
              : "//www.spoorts.cn/static/images/per-head-exp.png";
            //this.getinfo();

            //mock
            //response.data.data.bind.idnum = "";

            //获取用户信息 如果没有证件号或者手机号就要去完善资料improve_user_information.vue页面

            //console.log(response)
            response.data.data.bind.forEach(function(item, index) {
              let array = {
                list: [
                  {
                    label: "证件号",
                    value: hiddenInfo(item.idnum)
                  },
                  {
                    label: "手机号",
                    value: hiddenInfo(item.mobile)
                  }
                ],
                buttons: [
                  {
                    style: "primary",
                    text: "修改资料",
                    onButtonClick: () => {
                      //_this.$router.push({
                      //  path: `improve_user_information?bid=${item.bid}`
                      // });
                      _this.bidTel = item.mobile;
                      _this.bidId = item.bid;
                      _this.show = true;
                    }
                  }
                ]
              };
              _this.list1.push(array);
              //console.log('-+_+_+')
              //console.log(_this.list)
            });
            //this,list.push([])

            if (response.data.data.bind.length == 0) {
              this.isShow = true;
              //this.$router.push({ path: "improve_user_information" });
            }
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg,
              onHide() {
                window.localStorage.setItem("isLogin", "false");
                cookie.remove("_sid");
                _this.$router.push({ path: "login" });
              }
            });
          }
        });
    },
    fileChanged() {},
    editPortrait() {
      let _this = this;
      document.querySelector(".vux-header-more").className += " needsclick";
      document.querySelector(".vue-uploader input").click();
      //document.querySelector(".vue-uploader input").click();

      //_this.$refs.input.click();
      //_this.$refs.input.click();

      //console.log(this.$refs.inpput);
      //this.$refs.inpput.click();
    },
    saveName() {
      let _this = this;
      this.axios
        .post(
          `${host}user/auth/modify`,
          qs.stringify({
            username: this.name
          })
        )
        .then(response => {
          if (response.data.code == "200") {
            this.$vux.toast.show({
              type: "text",
              text: "修改姓名成功",
              onHide() {
                _this.$router.push({ path: "/user" });
              }
            });
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
    },
    loginOut() {
      this.axios.post(`${host}user/auth/logout`).then(response => {
        if (response.data.code == "200") {
          cookie.remove("_sid");
          //alert(cookie.get("_sid"))
          window.localStorage.setItem("isLogin", "false");
          this.$router.push({ path: "login" });
        } else {
          this.$vux.toast.show({
            type: "warn",
            text: response.data.msg
          });
        }
      });
    }
  },
  directives: {
    TransferDom
  },
  components: {
    Signedlist,
    Mypreview,
    Scroller,
    ViewBox,
    Spinner,
    Icon,
    Upfile,
    XHeader,
    CellBox,
    debounce,
    XInput,
    Group,
    XButton,
    Grid,
    GridItem,
    FormPreview,
    Cell,
    LoadMore,
    Actionsheet,
    Toast,
    Myheader,
    Confirm,
    MyFooter
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" rel="stylesheet/less">
#user {
  .userinfo {
    padding-bottom: 20px;
    text-align: center;
    img {
      max-width: 100px;
    }
    .fa {
      padding-right: 10px;
    }
  }
}

#user .userinfo {
  padding-top: 0;
}

#user {
  h2 {
    font-size: 30px;
    margin: 30px 0 30px 10px;
    text-align: center;
    margin-top: 0;
  }
  // 去除group的margintop
  .top-group {
    width: 100%;
  }
  .index-topf {
    margin-bottom: 100px;
    padding-top: 30px;
    .tips {
      padding: 10px 15px;
    }
  }

  .fa-no {
    color: #ddd;
    font-size: 28px;
  }
  .fa-home {
    color: #fff;
  }
  .weui-grid__icon {
    margin-bottom: 10px;
    pointer-events: none;
  }
  .weui-grid__label {
    pointer-events: none;
  }

  // 详情页
  .index-tops {
    margin: 30px 0 30px 0;
    margin-top: 0;
    padding-top: 30px;
    .gridbox {
      border-bottom: 1px solid #d9d9d9;
      .weui-grid:after {
        border: none;
      }
    }
    .cancel-button {
      margin-top: 15px;
      display: flex;
    }
    .grid-center {
      display: block;
      text-align: center;
      color: #666;
    }
    .gridbox {
      .weui-grid:before {
        border-right: none;
      }
    }
    // 去除选手信息列表的线
    .weui-loadmore_line .weui-loadmore__tips {
      padding: 0;
    }
  }
}

#user .userinfo {
  padding-bottom: 0;
}

#user .userinfo .fa-home {
  padding-right: 0;
}

#bind-message .weui-form-preview__hd {
  display: none;
}

#postcode input {
  border: 1px solid #eeeeee;
  max-width: 90px;
  height: 30px;
  border-radius: 8px;
  text-align: left;
  text-indent: 0.5em;
}

#postcode .weui-cell__bd {
  text-align: left;
}

#userinfo .weui-dialog__bd .button.weui-btn {
  margin-top: 0;
}

#userinfo .weui-form-preview__hd {
  text-align: left;
}

#userinfo .weui-form-preview__hd .weui-form-preview__label {
  float: none;
  display: inline-block;
  max-width: 40%;
}

#userinfo .weui-form-preview__hd .weui-form-preview__value {
  float: right;
  max-width: 50%;
}

#userinfo .vux-header-title-area {
  text-align: center;
  line-height: 40px;
}

#userinfo .weui-tab__panel {
  padding-bottom: 0px;
}

#user h2 {
  font-size: 30px;
  line-height: 2;
  text-align: center;
  color: #25a2ff;
}

#user .weui-form-preview__hd {
  text-align: left;
}

#user .weui-form-preview__hd .weui-form-preview__label {
  float: none;
  display: inline-block;
  max-width: 40%;
}

#user .weui-form-preview__hd .weui-form-preview__value {
  float: right;
  max-width: 50%;
}

#user .vux-header-title-area {
  text-align: center;
  line-height: 40px;
}

#user .weui-tab__panel {
  padding-bottom: 0px;
}

#user .vux-cell-primary {
  text-align: left;
}

#user .weui-form-preview__hd .weui-form-preview__value {
  font-style: normal;
  font-size: 1.3em;
}
</style>






